import pyautogui
from PIL import Image
from PIL import ImageGrab
import time

import tkinter as tk
import os
import pyperclip

def take_screenshot():
    print("Move your mouse to the top-left corner and press Enter...")
    input()
    x1,y1 = pyautogui.position()
    print(f"Top-left coner set at ({x1},{y1})")


    print("Move your mouse to the bottom-right corner and press Enter...")
    input()
    x2,y2 = pyautogui.position()
    print(f"Top-left coner set at ({x2},{y2})")
# take_screenshot()

class ScreenshotTool:
    def __init__(self, root):
        self.root = root
        self.root.attributes('-alpha', 0.2)  # 半透明
        self.root.attributes('-fullscreen', True)
        self.canvas = tk.Canvas(root, cursor="cross")
        self.canvas.pack(fill=tk.BOTH, expand=tk.YES)
        
        self.start_x = None
        self.start_y = None
        self.rect = None

        self.canvas.bind("<ButtonPress-1>", self.on_button_press)
        self.canvas.bind("<B1-Motion>", self.on_move_press)
        self.canvas.bind("<ButtonRelease-1>", self.on_button_release)

    def on_button_press(self, event):
        # 鼠标按下
        self.start_x = self.canvas.canvasx(event.x)
        self.start_y = self.canvas.canvasy(event.y)
        self.rect = self.canvas.create_rectangle(self.start_x, self.start_y, self.start_x, self.start_y, outline='red', width=2)

    def on_move_press(self, event):
        # 鼠标拖动
        cur_x, cur_y = (self.canvas.canvasx(event.x), self.canvas.canvasy(event.y))
        self.canvas.coords(self.rect, self.start_x, self.start_y, cur_x, cur_y)

    def on_button_release(self, event):
        # 鼠标释放
        end_x = self.canvas.canvasx(event.x)
        end_y = self.canvas.canvasy(event.y)
        
        # 退出 Tkinter 窗口
        self.root.quit()
        self.root.attributes('-alpha', 0)  # 恢复透明度再截图
        time.sleep(0.5)

        # 进行截图
        x1 = int(min(self.start_x, end_x))
        y1 = int(min(self.start_y, end_y))
        x2 = int(max(self.start_x, end_x))
        y2 = int(max(self.start_y, end_y))
        
        pyperclip.copy(f"{x1},{y1}")
        print(f"copy {x1},{y1} ok")

        global color_x,color_y
        color_x,color_y = x1,y1
        # screenshot = ImageGrab.grab()
        # color = screenshot.getpixel((x1, x1))
        # print(f"The color at position ({x1}, {x1}) is: {color}")
        
        

if __name__ == "__main__":
    # time.sleep(2)
    root = tk.Tk()
    app = ScreenshotTool(root)
    root.mainloop()

    screenshot = ImageGrab.grab()
    color = screenshot.getpixel((color_x, color_y))
    print(f"The color at position ({color_x}, {color_y}) is: {color}")

